<?php



class Database {

	
	//fichier détaillant les connexions possibles
	const CONFIG_FILE='cfg/connection.cfg.php';
	

	//instance de connection
	protected static $connexion=null;
	protected static $schema='';


	//tentative de connection à la base mysql
	protected static function connect() {
	
		//on vérifie quand même si on est pas déjà connecté
		if(self::$connexion==null){

			//récupération des chaines de connexion
			require(self::CONFIG_FILE);
			
			//pour toutes les connexions dans le fichier de config
			for($i=0; $i<count($connect); $i++){
				//on tente une connexion
				self::$connexion = new mysqli(
						$connect[$i]['serveur'],
						$connect[$i]['login'],
						$connect[$i]['mdp'],
						$connect[$i]['schema']);
				//si elle s'est bien passé
				if(!self::$connexion->connect_errno) {
					self::$schema=$connect[$i]['schema'];
					//on n'en tente pas d'autres
					break;
				}
				else{
					$noError=self::$connexion->connect_errno;
					$nom=$connect[$i]['serveur'];
					Message::log("Erreur $noError lors de la connection [$nom]");
				}
			}
			if(self::$connexion===null){
				Message::crash("Aucune connexion à une base de données n'a pu être établie");
				Security::errorPage();
			}
			
		}
	}
	
	
	protected static function query($str_requete){
		self::connect();
		Message::debug($str_requete);
		$result=self::$connexion->query($str_requete);
		if(!$result){
			Message::log('SQL ERROR '.mysqli_errno(self::$connexion).' : '.mysqli_error(self::$connexion));
		}
		return $result;
	}
	
	
	public static function getTableMeta($table){
		self::connect();
		$result=self::query("SELECT table_comment as comment FROM information_schema.tables ".
				"WHERE table_schema='".self::$schema."' AND table_name='$table';");
		if($ligne=mysqli_fetch_assoc($result)){
			return $ligne;
		}
		return array(
			'comment'=>''
		);
	}
	
	
	public static function getColumnMeta($table, $colonne){
		self::connect();
		$result=self::query("SELECT column_comment as comment FROM information_schema.columns ".
				"WHERE table_schema='".self::$schema."' AND table_name='$table' AND column_name='$colonne';");
		if($ligne=mysqli_fetch_assoc($result)){
			return $ligne;
		}
		return array(
			'comment'=>''
		);
	}
	
	
	public static function loadElement($table, $pk, $value){
		return self::query("SELECT * FROM $table WHERE $pk='$value';");
	}
	
	
	public static function countElements($table){
		$result = self::query("SELECT count(*) as nb FROM $table");
		$ligne=mysqli_fetch_assoc($result);
		return $ligne['nb']*1;
	}
	
	
	public static function loadTable($table, $from=null, $to=null, $order=''){
		if($from==null) $from=0;
		if($to==null) $to=self::countElements($table);
		return self::query("SELECT * FROM $table $order LIMIT $from, $to");
	}
	
	
	public static function selectList($select){
		$result=self::query($select);
		$retour=array();
		while($ligne=mysqli_fetch_assoc($result)){
			$retour[]=$ligne;
		}
		return $retour;
	}
	
	
	public static function update($table, $values, $pk, $pkVal){
		$modifs='';
		foreach($values as $key => $val){
			if($modifs!=''){
				$modifs.=',';
			}
			//on remplace les valeurs null par NULL (sql) et
			//on les apostrophes par des doubles apostrophes
			$sqlVal=($val===null?'NULL':"'".str_replace("'","''",$val)."'");
			$modifs.="$key=$sqlVal";
		}
		$str_requete="UPDATE $table SET $modifs WHERE $pk='$pkVal';";
		Message::log($str_requete);
		return self::query($str_requete);
	}
	
	
	public static function insert($table, $values){
		$colonnes='';
		$valeurs='';
		foreach($values as $key => $val){
			if($colonnes!=''){
				$colonnes.=',';
				$valeurs.=',';
			}
			$colonnes.=$key;
			$valeurs.=($val===null?'NULL':"'$val'");
		}
		$str_requete="INSERT INTO $table ($colonnes) VALUES ($valeurs);";
		Message::log($str_requete);
		return self::query($str_requete);
	}
	
	
	public static function delete($table, $pk, $pkVal){
		$str_requete="DELETE FROM $table WHERE $pk='$pkVal';";
		Message::log($str_requete);
		return self::query($str_requete);
	}
	
	
	public static function truncate($table){
		$str_requete="DELETE FROM $table;";
		Message::log($str_requete);
		return self::query($str_requete);
	}
	
	
	protected static function getListe($str_requete){
		$result=self::query($str_requete);
		$liste=array();
		while($tuple=mysqli_fetch_assoc($result)){
			$liste[]=$tuple;
		}
		return $liste;
	}
    
    
    protected static function getSchema(){
        self::connect();
        return self::$schema;
    }


}

?>